//
//  SLStartPage.swift
//  sulit-loan
//
//  Created by 王刚锋 on 2025/4/5.
//  Copyright © 2025 coolBoy. All rights reserved.
//

import UIKit
import AdSupport
import Network
import CoreLocation
import AppTrackingTransparency
import FBSDKCoreKit
import Alamofire
import MBProgressHUD
import CoreTelephony

class SLStartPage: SLBaseVC {
    
    let queue = DispatchQueue.global(qos: .default)
    var locationStatus: Bool = false
    let networkMontor = NetworkMonitor()

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.backgroundImageV.image = IMAGE("背景")
        self.appName.isHidden = false
        self.logo.isHidden = false
        self.startBtn.isHidden = true
        networkMontor.startMonitoring()
        
    }
    @objc override func NetworkReachEventAction() {
        DispatchQueue.main.async {
            self.checkStatus()
        }
    }
    @objc override func NetworkBreakEventAction() {
        DispatchQueue.main.async { [self] in
            if self.view.contains(startBtn) {
                self.startBtn.isHidden = false
            }
        }
    }
    func checkStatus(){
        
//        if let baseurl = __valueForKey(key: "baseUrl") as? String{
//            print("更改域名:" + baseurl)
//        }
        let mbp = MBProgressHUD.showMessage(message: "")
        let languageCode = Locale.current.languageCode
        SLHttpTool.AsyncReportData(path: "/satisfies/fifth", params: ["eurosport":languageCode ?? "en","somewhere":"0","imitation":"0"], target: self) { responseData, success, msg, code in
            mbp.hide(animated: true)
            
            if success{
                let wavelets = responseData["wavelets"]
                __setValue(value: wavelets["hair"].stringValue, key: kHair)
                __setValue(value: wavelets["tufts"]["hand"].stringValue, key: kNum)
                __setValue(value: wavelets["flush"].intValue, key: kFlush)
                
                __setValue(value: wavelets["veins"].stringValue, key: KProtocol)
                
                let inflated = wavelets["inflated"]
                Settings.shared.appID = inflated["whiskers"].stringValue
                Settings.shared.displayName = inflated["tubular"].stringValue
                Settings.shared.clientToken = inflated["ordered"].stringValue
                Settings.shared.appURLSchemeSuffix = inflated["vibrissas"].stringValue
                Settings.shared.isAutoLogAppEventsEnabled = true
                ApplicationDelegate.shared.application(UIApplication.shared, didFinishLaunchingWithOptions: nil)

                SLHttpTool.uploadDevData()
                self.getCityData()
                self.checkSuccess()
            }else{
                self.updateRealm()
            }
        }
    }
    func getCityData(){
        SLHttpTool.AsyncReportData(path: "/satisfies/menecrates", target: self) { data, success, msg, code in
            if success {
                let cityArr = data["wavelets"]["quite"].arrayObject
                __setValue(value: cityArr, key: KCityList)
                
            }
        }
    }
    func updateRealm(){
  
        
        SLHttpTool.AsyncReportData(path: "https://ph02-ios-dc.oss-ap-southeast-6.aliyuncs.com/sulit-loan/Dgq1fcKwtQzqsH9s.json",method:.get, target: self) { data, success, msg, code in
            let arr = data.arrayValue
            let array = arr.map { json in
                json["sl"].stringValue
            }
            if array.count > 0{}else{
//                self.checkStatus()
                self.startBtn.isHidden = false
                return
            }
            var url = SLAPIConfig.baseURL
            if let baseurl = __valueForKey(key: "baseUrl") as? String{
                url = baseurl
            }
            if array.contains(url){
                for i in 0...array.count-1{
                    let str = array[i]
                    if url == str {
                        var index = i + 1
                        if index >= array.count {index = 0}
                        let base = array[index]
                        __setValue(value: base, key: "baseUrl")
                        break
                    }
                }
            }else{
                    let base = array.first
                    __setValue(value: base, key: "baseUrl")
                }
            self.checkStatus()
            }
    }

    func checkSuccess(){
        
        if let guide = __valueForKey(key: "isguide") {
            if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
                appDelegate.jumpMainVC()
            }
        }else{
            if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
                appDelegate.showGuide()
                __setValue(value: 1, key: "isguide")
                
            }
        }
    }
    
    
    lazy var logo:UIImageView = {
        let v = create_imageView(image: IMAGE("Rectangle 34626979"), supView: self.view) { make in
            make.width.height.equalTo(92)
            make.centerY.equalToSuperview().offset(-35)
            make.centerX.equalToSuperview()
        }
        return v
    }()
    lazy var appName:UIImageView = {
        let v = create_imageView(image: IMAGE("logo"), supView: self.view) { make in
            make.width.height.equalTo(94)
            make.height.equalTo(28);
            make.top.equalTo(logo.snp.bottom).offset(8)
            make.centerX.equalToSuperview()
        }
        return v
    }()
    lazy var startBtn:UIButton = {
        let v = create_button(title: "Start", titleColor: .white, titleFont: SLFontConfig.medium16,bgColor: rgba(hex: "#1608EC"), image: nil, supView: self.view, closure: { make in
            make.width.equalTo(280)
            make.height.equalTo(44)
            make.bottom.equalTo(-48)
            make.centerX.equalToSuperview()
        }, selector: (target:self, action: #selector(startClick), event: .touchUpInside))
        v.isHidden = true
        v.layer.masksToBounds = true
        v.layer.cornerRadius = 22
        return v
    }()
    @objc func startClick(){
        startBtn.isHidden = true
        checkStatus()
    }

}
extension SLStartPage {
    override func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
           if let location = locations.first {
               let geocoder = CLGeocoder()  // 新增地理编码器
               let loc = CLLocation(latitude: Double(location.coordinate.latitude), longitude: Double(location.coordinate.longitude))
               geocoder.reverseGeocodeLocation(loc) { (placemarks, error) in
                   if error != nil {
                       
                   } else if let placemarks = placemarks {
                       let latitude = "\(location.coordinate.latitude)"
                       let longitude = "\(location.coordinate.longitude)"
                       let placemark = placemarks[0]
                       let params:[String:Any] = ["thomas":placemark.locality ?? "",
                                                  "ubudiah":placemark.isoCountryCode ?? "",
                                                  "neo":placemark.country ?? "",
                                    "malaysia":placemark.thoroughfare ?? "",
                                    "indra":latitude,
                                    "weapon":longitude,
                                    "trishul":placemark.locality ?? "",
                                    "repeated":placemark.subLocality ?? ""]
                       
                       __setValue(value: latitude, key: "latitude")
                       __setValue(value: longitude, key: "longitude")

                       SLHttpTool.AsyncPointData(path: "/satisfies/masarh",params: params, target: self) { responseCall, success, msg, code in
                       }
                   }
               }
               // 获取到位置信息后，停止更新位置，节省电量
               manager.stopUpdatingLocation()

           }
       }
    override func locationManager(_ manager: CLLocationManager, didFailRangingFor beaconConstraint: CLBeaconIdentityConstraint, error: Error) {
        print(error)
    }
    override func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print(error)
        self.startBtn.isHidden = false
        
    }
    // 实现代理方法，处理权限请求的结果
    override func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
//        manager.stopUpdatingLocation()
        switch status {
        case .authorizedWhenInUse, .authorizedAlways,.restricted:
            print("定位权限被授予")

            // 开始获取位置信息
        case .denied:
            self.locationStatus = false
            print("定位权限被拒绝")
            // 引导用户到设置去开启权限
            DispatchQueue.main.async {
//                self.bottomBtn.isHidden = false
                
            }
        default:
            break
        }
    }

}
